﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ZipAligner
{
    public partial class Form2 : Form
    {
        private delegate void GUIUs(string sVal);
        private System.Collections.ArrayList foundFiles = new System.Collections.ArrayList();
        private Thread alignThr;
        private string[] valueStr=new string[3];
        private Form fParent;
        public Form2(Form parentForm,string inPath,string outPath,string fileExt)
        {
            fParent = parentForm;
            valueStr[0] = inPath; valueStr[1] = outPath; valueStr[2] = fileExt;
            InitializeComponent();
        }
        private void updateUI(string prsStr)
        {
            if (InvokeRequired)
            {
                GUIUs uiu = new GUIUs(updateUI);
                Invoke(uiu, new object[] { prsStr });
            }
            else
            {
                if (prsStr == "::F")
                {
                    Close();
                    return;
                }
                else
                {
                    label1.Text = "Aliging: " + prsStr;
                }
            }
        }
        private void mainWork()
        {
            string[] files = Directory.GetFiles(valueStr[0]);
            string binDir = Path.Combine(System.Environment.GetEnvironmentVariable("TEMP"), "zipalign.exe");
            File.Copy("zipalign_exe.bin", binDir, true);
            foreach (string tFile in files) {
                if (Path.GetExtension(tFile) == valueStr[2])
                {
                    updateUI(Path.GetFileName(tFile));
                    Process bkCmd = new Process();
                    bkCmd.StartInfo.FileName = binDir;
                    bkCmd.StartInfo.Arguments = "-f 4 \"" + tFile + "\" \"" + Path.Combine(valueStr[1], Path.GetFileName(tFile)) + "\"";
                    //bkCmd.StartInfo.UseShellExecute = false;
                    bkCmd.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    bkCmd.Start();
                    bkCmd.WaitForExit();
                }
            }
            updateUI("::F");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (alignThr.IsAlive)
                alignThr.Abort();
            fParent.Show();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            alignThr = new Thread(new ThreadStart(mainWork));
            alignThr.Start();
        }
    }
}
